<script setup lang="tsx">
import { agentListApi, acctBalanceQueryApi } from '@/api/Agent'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useI18n } from '@/hooks/web/useI18n'
import { useTable } from '@/hooks/web/useTable'
import { useRoute, useRouter } from 'vue-router'
import { AgentLevelDict, dictToList } from '@/utils/dict'
import { ElButton } from 'element-plus'

const { t } = useI18n()
const { push } = useRouter()
const { query } = useRoute()
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await agentListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      businessId: unref(query.id as any),
      ...unref(searchParams)
    })
    return {
      list: res.data.list || [],
      total: res.data.total || 0
    }
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList } = tableMethods

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: 'ID',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  // {
  //   field: 'businessName',
  //   label: '商家简称',
  //   search: {
  //     componentProps: {
  //       placeholder: '请输入商家简称'
  //     }
  //   },
  //   form: {
  //     hidden: true
  //   },
  //   table: {
  //     hidden: true
  //   }
  // },
  {
    field: 'nickName',
    label: '经纪人',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      width: 220,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div class={'flex items-center'}>
                <img class={'w-10 mr-2'} src={row.avatar} />
                <span>{row.nickName}</span>
              </div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'realName',
    label: '真实姓名',
    search: {
      componentProps: {
        placeholder: '请输入姓名'
      }
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'mobile',
    label: '经纪人手机号',
    search: {
      componentProps: {
        placeholder: '请输入经纪人手机号'
      }
    },
    form: {
      hidden: true
    },
    table: {
      width: 120
    }
  },
  {
    field: 'agentLevel',
    label: '层级',
    search: {
      component: 'Select',
      componentProps: {
        options: dictToList(AgentLevelDict)
      }
    },
    form: {
      hidden: true
    },
    table: {
      width: 120,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <span>{AgentLevelDict[row.agentLevel]}</span>
            </>
          )
        }
      }
    }
  },
  {
    field: 'agentMobile',
    label: '上级经纪人',
    search: {
      componentProps: {
        placeholder: '请输入上级经纪人手机号'
      }
    },
    form: {
      hidden: true
    },
    table: {
      width: 120,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div>{row.agentNickName}</div>
              <div>{row.agentMobile}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'totalOrderCount',
    label: '总分销订单数',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'totalOrderAmt',
    label: '总分销订单金额',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'relationBusinessCount',
    label: '关联商家数',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return row.agentLevel === 2 ? 0 : row.relationBusinessCount
        }
      }
    }
  },
  {
    field: 'totalCommission',
    label: '累计分销佣金',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'totalWithdrawalCommission',
    label: '累计提现金额',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'commissionAmt',
    label: '佣金账户余额',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'hfId',
    label: '签约状态',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      width: 80,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div>{row.hfId ? '已签约' : '未签约'}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'hfId',
    label: '汇付ID',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      width: 160
    }
  },
  {
    field: 'hfBalance',
    label: '汇付账户余额',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      width: 80,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          if (row.hfId) {
            return (
              <>
                <div>{row.hfBalance}</div>
                <ElButton type="primary" link onClick={() => queryHfBalance(row)}>
                  查询
                </ElButton>
              </>
            )
          }
        }
      }
    }
  },
  {
    field: 'enterTime',
    label: '加入时间',
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    form: {
      hidden: true
    },
    table: {
      width: 220
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 100,
      slots: {
        default: (data: any) => {
          const row = data.row
          if (row.agentLevel === 1) {
            return (
              <>
                <ElButton type="primary" link onClick={() => business(row)}>
                  关联商家
                </ElButton>
              </>
            )
          }
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)
const business = (row) => {
  push(`/agent/detail?id=${row.id}`)
}
const queryHfBalance = async (row) => {
  const res = await acctBalanceQueryApi({ hfId: row.hfId })
  const info = JSON.parse(res.data.data.acctInfo_list)
  row.hfBalance = info[0].balance_amt
}
const searchParams = ref({})
const setSearchParams = (params: any) => {
  const { enterTime, ...rest } = params
  let startTime, endTime
  if (enterTime && enterTime.length > 0) {
    startTime = enterTime[0]
    endTime = enterTime[1]
  }
  currentPage.value = 1
  searchParams.value = {
    startTime,
    endTime,
    ...rest
  }
  getList()
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="flex-[3] ml-20px">
      <Search
        :schema="allSchemas.searchSchema"
        @reset="setSearchParams"
        @search="setSearchParams"
      />
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentWrap>
  </div>
</template>
